#include <stdlib.h>
#include <string.h>

#include <glib.h>

#include "totem-plugin.h"
#include "totem-private.h"
#include "totem.h"

#include "totem-lrc.h"
#include "totem-lrc-func.h"
#include "totem-lrc-pad.h"
#include "totem-lrc-down.h"

extern const gchar *lrc_keys[PLUGIN_LAST_KEYS+1];

void totem_lrc_keys(void)
{
	if(lrc_keys[0])
		return ;
	lrc_keys[PLUGIN_NAME]="totem_lrc";
	lrc_keys[PLUGIN_LRC_PATHS]="path";
	lrc_keys[PLUGIN_WIN_MODEL]="win_model";
	lrc_keys[PLUGIN_SIDE_BAR]="LyricsShow";
	lrc_keys[PLUGIN_ENGINEER]="PlugEng";
	lrc_keys[PLUGIN_LAST_KEYS]= NULL;
}

void free_minfo(MataInfo *m)
{
	g_free(m->artist);
	g_free(m->title);
	g_free(m->path);
	g_free(m->url);
	tt_free_list(m->list);
	if(m->lyricfile_w == m->lyricfile_r)
		g_free(m->lyricfile_w);
	else{
		g_free(m->lyricfile_w);
		g_free(m->lyricfile_r);
	}
	lmp_debug("g_freed");

	m->artist = NULL;
	m->title = NULL;
	m->path = NULL;
	m->lyricfile_w = NULL;
	m->lyricfile_r = NULL;
	m->list = NULL;
	m->url = NULL;
}

gchar *encode_back_to_originally(const gchar *str)
{
	GError* error = NULL;
	if(!str)
		return NULL;
	/*
	 * totem think everything is iso-8859-1 ;then convert it to  utf8;
	 * so back to originally
	 */
	gchar* pgb = g_convert(str, -1, "iso-8859-1", "utf-8", NULL, NULL, &error);
	if(error)
	{
		lmp_debug("g_convert: %s", error->message);
		g_error_free(error);
		return g_strdup(str);
	}
//	lmp_debug(pgb);
	return pgb;
}

gchar *totem_lrc_plugin_encode_to_utf8(TotemLrcPlugin*plugin,const gchar *str)
{
	const gint max_loop = 16;
	gchar **code = NULL;
	gchar *new_str = NULL;
	gsize r=0,w=0;
	int i = 0;
	if(!str)
		return NULL;

	if(g_utf8_validate (str,-1,NULL))
		return g_strdup(str);

	code = plugin->default_code;
	while( i<max_loop && code[i]){ /* make sure that have no death loop */
		new_str = g_convert(str,-1,"utf-8",code[i],&r,&w,NULL);
		if(new_str){
			lmp_debug("code[%d]:%s.",i,code[i]);
			return new_str;
		}else{
			new_str = g_locale_to_utf8(str,-1,&r,&w,NULL);
			if(new_str)
				return new_str;
		}
		i++;
	}
	lmp_debug("NULL");
	return NULL;
}

gchar *remove_ch(gchar *str,gchar ch)
{
	int i = 0;
	int j = 0;
	for(;str[j];j++)
		if(str[j]==ch)
			break;
	while(str[j]){
		while(str[j+i]==ch){
			i++;
		}
		str[j]=str[j+i];
		if(!str[j])
			break;
		j++;
	}
	return str;
}

gchar *get_addr(gchar *str,char ch)
{
	char *tmp=str;
	while(*tmp){
		if(*tmp==ch)
			return ++tmp;
		tmp++;
	}
	return *tmp?str:NULL;
}

char *get_addr_last(char *str,char ch)
{
	int i=0,j=0;
	while(str[i]){
		if(str[i++]==ch)
			j=i;
	}
	return str+j;
}

void set_a_to_b(gchar *str,char a,char b)
{
	while(*str){
		if(*str==a)
			*str = b;
		str++;
	}
}

gint64 read_time_at_line(gchar *line)
{
	gint64 t=0;
	gchar *str = line;
///	lmp_debug(line);
	if(str[1]>'9'||str[1]<'0'){
		lmp_debug("not time at begin .");
		return 0;
	}

	str++;

	t = atoll(str)*60*1000;
///	lmp_debug("t:%ld",t);
	t = t+atof(get_addr(str,':'))*1000;
///	lmp_debug("t:%ld",t);

	return t<0?-t:t;///Can time be negative ?

}
